import { Author } from "@/type/author";
import { Button, Icon } from "annar";
import * as React from "react";
import { usePageEvent } from "remax/macro";
import { origin } from "@/config/config";

export type Prop = {
  isFollow: boolean;
  authorId: string;
  style?: React.CSSProperties;
};

export default (prop: Prop) => {
  const [isFollow, setIsFollow] = React.useState<boolean>(prop.isFollow);
  const [followBtnColor, setFollowBtnColor] = React.useState<string>("");
  const [followIconColor, setFollowIconColor] = React.useState<string>("");
  const [followText, setFollowText] = React.useState<string>("");
  const authorId = prop.authorId;
  React.useEffect(() => {
    if (isFollow) {
      setFollowBtnColor("light");
      setFollowIconColor("check");
      setFollowText("已关注");
    } else {
      setFollowBtnColor("orange");
      setFollowIconColor("add");
      setFollowText("关注");
    }
  }, [prop.isFollow]);

  const bindFollow = () => {
    let isFollow: boolean = followBtnColor === "light";
    setFollowBtnColor(followBtnColor === "orange" ? "light" : "orange");
    setFollowIconColor(followIconColor === "check" ? "add" : "check");
    setFollowText(followText === "关注" ? "已关注" : "关注");
    let loginInfo = wx.getStorageSync("loginInfo");
    if (isFollow) {
      // 已经关注了取消关注
      wx.request({
        url: `${origin}/follow/undo/${authorId}`,
        header: {
          token: loginInfo.token,
        },
        success: (res: any) => {
          console.log(res.data.data);
        },
      });
    } else {
      // 没有关注, 去关注
      wx.request({
        url: `${origin}/follow/do/${authorId}`,
        header: {
          token: loginInfo.token,
        },
        success: (res: any) => {
          console.log(res.data.data);
        },
      });
    }
  };

  return (
    <Button
      style={prop.style}
      onTap={bindFollow}
      shape="square"
      block
      look={followBtnColor}
      size="large"
      icon={
        <Icon type={followIconColor} color={followBtnColor} size={"40px"} />
      }
    >
      {followText}
    </Button>
  );
};
